package com.qilin.hscs.hm.mqtt.service.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.qilin.hscs.hm.enums.ServiceFlushEnum;
import com.qilin.hscs.hm.mqtt.constant.HostNameConstant;
import com.qilin.hscs.hm.mqtt.handler.LogicHandleCentry;
import com.qilin.hscs.hm.pojo.Scene;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by 10188 on 2018/3/30.
 */
@Component
public abstract class ServiceCommon implements HostNameConstant {

    protected   String msg;
    protected   Integer cmd;
    protected   String topicVar;
    protected   JSONObject msgObj;
    protected   JSONObject dataObj;
    protected   String phone;

    private static final Logger logger= LogManager.getLogger(ServiceCommon.class.getName());

    @Autowired
    private LogicHandleCentry handler;

    protected final void flush() {
        Observable<String> observable= Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitter.onNext(serviceName+"#"+topicVar+"#"+msg);
            }
        });
        observable.subscribe(handler);
    }
   protected void isflushToGateway(boolean is){
        if (is) {
            msg += ServiceFlushEnum.handle_by_gateway.getCode();
            if (topicVar.contains("/rsp")) {
                topicVar = topicVar.substring(0, topicVar.indexOf('g'));
            }else {
                topicVar += "/g";
            }
        } else {
            if (topicVar != null) {
                if (!topicVar.contains("/rsp")) {
                    topicVar += "/rsp";
                }else {
                    int i = topicVar.indexOf("g");
                    topicVar = topicVar.substring(0, i) + "rsp";
                }
                msg += ServiceFlushEnum.not_handle_by_gateway.getCode();
            }
        }
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getTopicVar() {
        return topicVar;
    }

    public void setTopicVar(String topicVar) {
        this.topicVar = topicVar;
    }

    public void initailData(){
        try {
            msgObj = JSON.parseObject(msg);
            dataObj = msgObj.getJSONObject("data");
        } catch (JSONException je) {
            logger.warn("传输过来的json字符串有误，主机无法解析 错误详细情况为={}", je.getStackTrace());
        }
            cmd = msgObj.getInteger("cmd");
    }

    public abstract void handle();
}
